/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.vidmt.api.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.vidmt.api.common.jee.ValidateCodeServlet;
import com.vidmt.api.common.web.WebController;
import com.vidmt.api.modules.sys.shiro.MyPrincipal;
import com.vidmt.api.modules.sys.shiro.MyWebToken;

/**
 * 登录Controller
 * 
 * @author ThinkGem
 * @version 2013-5-31
 */
@Controller
public class WebLoginController extends WebController {

	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
	public String loginweb(HttpServletRequest request, HttpServletResponse response, Model model) {
		Subject subject = SecurityUtils.getSubject();
		MyPrincipal principal = (MyPrincipal) subject.getPrincipal();

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			CookieUtils.setCookie(response, "LOGINED", "false");
		}

		// 如果已经登录，则跳转到管理首页
		if (principal != null) {
			return "redirect:" + adminPath;
		}
		// String view;
		// view = "/WEB-INF/views/modules/sys/sysLogin.jsp";
		// view = "classpath:";
		// view +=
		// "jar:file:/D:/GitHub/jeesite/src/main/webapp/WEB-INF/lib/jeesite.jar!";
		// view += "/"+getClass().getName().replaceAll("\\.",
		// "/").replace(getClass().getSimpleName(), "")+"view/sysLogin";
		// view += ".jsp";
		return "modules/sys/sysLogin";
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
	public String login(String username, String password, String validateCode, boolean rememberMe,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		if (password == null) {
			password = "";
		}
		HttpServletRequest req = (HttpServletRequest) request;
		String host = StringUtils.getRemoteAddr(req);
		String captcha = validateCode;

		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(new MyWebToken(username, password.toCharArray(), rememberMe, host, captcha));
		} catch (AuthenticationException e) {
			model.addAttribute("message", "用户名或密码错误,请重试");
			return "modules/sys/sysLogin";
		}
		MyPrincipal principal = (MyPrincipal) subject.getPrincipal();

		// 如果已经登录，则跳转到管理首页
		if (principal != null) {
			return "redirect:" + adminPath;
		}

		model.addAttribute("username", username);
		model.addAttribute("rememberMe", rememberMe);
		// model.addAttribute("shiroLoginFailure", exception);
		// model.addAttribute("message", message);

		// 非授权异常，登录失败，验证码加1。
		// if (!UnauthorizedException.class.getName().equals(exception)) {
		// model.addAttribute("isValidateCodeLogin",
		// UserUtils.isValidateCodeLogin(username, true, false));
		// }

		// 验证失败清空验证码
		request.getSession().removeAttribute(ValidateCodeServlet.VALIDATE_CODE);

		return "modules/sys/sysLogin";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response,Model model) {
		Subject subject = SecurityUtils.getSubject();
		MyPrincipal principal = (MyPrincipal) subject.getPrincipal();

		// 登录成功后，验证码计算器清零
		UserUtils.isValidateCodeLogin(principal.getDisplayName(), false, true);

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)) {
				CookieUtils.setCookie(response, "LOGINED", "true");
			} else if (StringUtils.equals(logined, "true")) {
				UserUtils.getSubject().logout();
				return "redirect:" + adminPath + "/login";
			}
		}

		// 如果是手机登录，则返回JSON字符串
		// if (principal.isMobileLogin()) {
		// if (request.getParameter("login") != null) {
		// return renderString(response, principal);
		// }
		// if (request.getParameter("index") != null) {
		// return "modules/sys/sysIndex";
		// }
		// return "redirect:" + adminPath + "/login";
		// }

		// // 登录成功后，获取上次登录的当前站点ID
		// UserUtils.putCache("siteId",
		// StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));

		// System.out.println("==========================a");
		// try {
		// byte[] bytes =
		// com.thinkgem.jeesite.common.utils.FileUtils.readFileToByteArray(
		// com.thinkgem.jeesite.common.utils.FileUtils.getFile("c:\\sxt.dmp"));
		// UserUtils.getSession().setAttribute("kkk", bytes);
		// UserUtils.getSession().setAttribute("kkk2", bytes);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//// for (int i=0; i<1000000; i++){
		//// //UserUtils.getSession().setAttribute("a", "a");
		//// request.getSession().setAttribute("aaa", "aa");
		//// }
		// System.out.println("==========================b");
		model.addAttribute("menuList", UserUtils.getAllMenuList());
		return "modules/sys/sysIndex";
	}

	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtils.isNotBlank(theme)) {
			CookieUtils.setCookie(response, "theme", theme);
		} else {
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:" + request.getParameter("url");
	}

}
